package com.sum.common.manager;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.sum.common.bean.UHFDeviceType;
import com.sum.common.inter.IUHFManager;
import com.sum.common.utils.LogU;

public class UHFManager {
    private static volatile UHFManager instance;
    private static final String DEFAULT_PORT = "/dev/ttyS1";
    private static final String S2_PORT = "/dev/ttyS2";
    private static final int DEFAULT_BAUD_RATE = 115200;
    private static final int RONGRUI_ALTERNATE_BAUD_RATE = 57600;
    private static final Object lock = new Object();
    private static final long DELAY_TIME = 500L;

    private static final String PREF_NAME = "uhf_manager_prefs";
    private static final String KEY_LAST_DEVICE = "last_connected_device";
    private static final String KEY_LAST_PORT = "last_connected_port";

    private IUHFManager xinlianManager;
    private IUHFManager guoxinManager;
    private IUHFManager rongruiManager;
    private IUHFManager currentManager;
    private static String mCurPort = DEFAULT_PORT;

    private Context context;
    private UHFDeviceType tryDeviceType = UHFDeviceType.ALL;

    public interface ConnectCallback {
        void onSuccess(IUHFManager manager);
        void onFailed(String error);
    }

    public void setContext(Context context) {
        this.context = context;
        LogU.d("UHFManager: Context 设置成功！");
        loadConfig(); 
    }

    private UHFManager() {
        initializeManagers();
    }

    public static UHFManager getInstance() {
        if (instance == null) {
            synchronized (lock) {
                if (instance == null) {
                    instance = new UHFManager();
                }
            }
        }
        return instance;
    }

    private void initializeManagers() {
        try {
            IUHFManager manager = (IUHFManager) Class.forName("com.example.lib_xinlian.XinlianUHFManager")
                    .getDeclaredConstructor()
                    .newInstance();
            xinlianManager = manager.getInstance();

            manager = (IUHFManager) Class.forName("com.panlin.lib_guoxin.GuoxinUHFManager")
                    .getDeclaredConstructor()
                    .newInstance();
            guoxinManager = manager.getInstance();

            manager = (IUHFManager) Class.forName("com.example.lib_rongrui.RongruiUHFManager")
                    .getDeclaredConstructor()
                    .newInstance();
            rongruiManager = manager.getInstance();
        } catch (Exception e) {
            LogU.d("UHFManager: 初始化 UHF 设备管理器失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    public void connect(ConnectCallback callback, UHFDeviceType deviceType) {
        LogU.d("UHFManager connect from stack:" + Log.getStackTraceString(new Throwable()));
        new Thread(() -> {
            try {
                LogU.d("UHFManager connect 开始连接");
                close();
                tryDeviceType = deviceType;
                Thread.sleep(2000);
                if (hasConfig()) {
                    tryDeviceType = getLastConnectedDevice();
                    mCurPort = getLastConnectedPort();
                }
                LogU.d("UHFManager connect DEFAULT_PORT tryDeviceType = " + tryDeviceType + " , mCurPort = " + mCurPort);

                // 1. 连接所有型号或者连接过保存的设备
                if (tryConnectWithPort(mCurPort, callback, tryDeviceType)) {
                    return;
                }
                sleepDelay();

                // 2. 尝试 S2_PORT
                LogU.d("UHFManager connect S2_PORT tryDeviceType = " + tryDeviceType + " , mCurPort = " + mCurPort);
                tryConnectWithPort(S2_PORT, callback, tryDeviceType);

            } catch (InterruptedException e) {
                LogU.d("UHFManager 连接被中断：" + e.getMessage());
                Thread.currentThread().interrupt(); // 重新设置线程的中断状态
            } catch (Exception e) {
                LogU.d("UHFManager 连接异常：" + e.getMessage());
                if (callback != null) {
                    callback.onFailed("Connection error: " + e.getMessage());
                }
            }
        }).start();
    }


    private boolean hasConfig(){
        UHFDeviceType lastDeviceType = getLastConnectedDevice();
        String lastPort = getLastConnectedPort();
        return lastDeviceType != null && lastPort != null;
    }

    private boolean tryConnectWithPort(String port, ConnectCallback callback, UHFDeviceType deviceType) {
        mCurPort = port;
        LogU.d("tryConnectWithPort 尝试连接端口：" + port);

        if (deviceType == UHFDeviceType.ALL) {
            LogU.d("tryConnectWithPort XINLIAN：" + port);
            if (tryConnectDevice(xinlianManager, DEFAULT_BAUD_RATE)) {
                currentManager = xinlianManager;
                saveLastConnectedDevice(UHFDeviceType.XINLIAN);
                saveLastConnectedPort(port);
                if (callback != null) callback.onSuccess(currentManager);
                return true;
            }
            sleepDelay();
            LogU.d("tryConnectWithPort GUOXIN：" + port);
            if (tryConnectDevice(guoxinManager, DEFAULT_BAUD_RATE)) {
                currentManager = guoxinManager;
                saveLastConnectedDevice(UHFDeviceType.GUOXIN);
                saveLastConnectedPort(port);
                if (callback != null) callback.onSuccess(currentManager);
                return true;
            }
            sleepDelay();
            LogU.d("tryConnectWithPort RONGRUI：" + port);
            if (tryConnectDevice(rongruiManager, DEFAULT_BAUD_RATE) ||
                    tryConnectDevice(rongruiManager, RONGRUI_ALTERNATE_BAUD_RATE)) {
                currentManager = rongruiManager;
                saveLastConnectedDevice(UHFDeviceType.RONGRUI);
                saveLastConnectedPort(port);
                if (callback != null) callback.onSuccess(currentManager);
                return true;
            }
        } else {
            return tryConnectSpecificDevice(deviceType, callback);
        }

        if (callback != null && mCurPort.equals(S2_PORT)) {
            callback.onFailed("端口 " + port + " 未找到 UHF 设备");
        }
        return false;
    }

    private boolean tryConnectSpecificDevice(UHFDeviceType deviceType, ConnectCallback callback) {
        if (deviceType == UHFDeviceType.GUOXIN && tryConnectDevice(guoxinManager, DEFAULT_BAUD_RATE)) {
            currentManager = guoxinManager;
            LogU.d("tryConnectSpecificDevice GUOXIN：" + deviceType);
        } else if (deviceType == UHFDeviceType.XINLIAN && tryConnectDevice(xinlianManager, DEFAULT_BAUD_RATE)) {
            LogU.d("tryConnectSpecificDevice XINLIAN：" + deviceType);
            currentManager = xinlianManager;
        } else if (deviceType == UHFDeviceType.RONGRUI &&
                (tryConnectDevice(rongruiManager, DEFAULT_BAUD_RATE) || tryConnectDevice(rongruiManager, RONGRUI_ALTERNATE_BAUD_RATE))) {
            LogU.d("tryConnectSpecificDevice RONGRUI：" + deviceType);
            currentManager = rongruiManager;
        } else {
            return false;
        }

        saveLastConnectedDevice(deviceType);
        saveLastConnectedPort(mCurPort);
        if (callback != null) callback.onSuccess(currentManager);
        return true;
    }

    private void sleepDelay() {
        try {
            Thread.sleep(DELAY_TIME);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        if (currentManager != null) {
            LogU.d("关闭 UHF 设备");
            currentManager.close();
            currentManager = null;
            sleepDelay();
        }
    }

    private boolean tryConnectDevice(IUHFManager manager, int baudRate) {
        return manager != null && manager.connect(mCurPort, baudRate);
    }

    public IUHFManager getCurrentManager() {
        if (currentManager == null) {
            throw new IllegalStateException("没有连接任何 UHF 设备");
        }
        return currentManager;
    }

    public Boolean isRongruiDevice() {
        return getCurrentManager() == rongruiManager;
    }

    public Boolean isGuoxinDevice() {
        return getCurrentManager() == guoxinManager;
    }

    public Boolean isXinlianDevice() {
        return getCurrentManager() == xinlianManager;
    }

    private void saveLastConnectedDevice(UHFDeviceType deviceType) {
        if (context == null) {
            LogU.d("UHFManager: context 为空，无法保存设备信息！");
            return;
        }

        LogU.d("UHFManager: 尝试保存设备类型 -> " + deviceType);
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        boolean success = prefs.edit().putString(KEY_LAST_DEVICE, deviceType.name()).commit();

        LogU.d(success ? "设备类型保存成功：" + deviceType : "设备类型保存失败！");
    }

    private UHFDeviceType getLastConnectedDevice() {
        if (context == null) return null;

        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        String deviceName = prefs.getString(KEY_LAST_DEVICE, null);

        LogU.d(deviceName != null ? "读取到上次成功连接的设备：" + deviceName : "未找到上次连接的设备记录");
        return deviceName != null ? UHFDeviceType.valueOf(deviceName) : null;
    }

    private void saveLastConnectedPort(String port) {
        if (context == null) {
            LogU.d("UHFManager: context 为空，无法保存端口信息！");
            return;
        }

        LogU.d("UHFManager: 尝试保存端口 -> " + port);
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        boolean success = prefs.edit().putString(KEY_LAST_PORT, port).commit();

        LogU.d(success ? "端口保存成功：" + port : "端口保存失败！");
    }

    private String getLastConnectedPort() {
        if (context == null) return null;

        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        String port = prefs.getString(KEY_LAST_PORT, null);

        LogU.d(port != null ? "读取到上次成功连接的端口：" + port : "未找到上次连接的端口记录");
        return port;
    }

    private void loadConfig() {
        if (context == null) {
            LogU.d("UHFManager: context 为空，无法加载配置信息！");
            return;
        }

        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        String lastDevice = prefs.getString(KEY_LAST_DEVICE, null);
        String lastPort = prefs.getString(KEY_LAST_PORT, null);

        if (lastDevice != null && lastPort != null) {
            LogU.d("加载配置信息成功：设备类型 = " + lastDevice + ", 端口 = " + lastPort);
            mCurPort = lastPort;
        } else {
            LogU.d("未找到上次连接的配置信息");
        }
    }
}



